const mongoose = require('mongoose');
const BaseModel = require('./base_model');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const config = require('../config');
const _ = require('lodash');

const TopicSchema = new Schema({
    title: { type: String },
    content: { type: String },
    author_id: { type: ObjectId },
    author_name: { type: String },
    avatar: { type: String, default: null }, // 作者头像地址
    top: { type: Boolean, default: false }, //置顶帖
    good: { type: Boolean, default: false }, //精华帖
    lock: { type: Boolean, default: false }, //被锁定主题
    reply_count: { type: Number, default: 0 }, //回复数
    visit_count: { type: Number, default: 0 }, //点击数
    collect_count: { type: Number, default: 0 }, //收藏数
    create_at: { type: Date, default: Date.now }, //创建时间
    update_at: { type: Date, default: Date.now }, //更新时间
    last_reply: { type: ObjectId }, //最后回复者ID
    last_reply_at: { type: Date, default: null }, //最后回复的时间
    content_is_html: { type: Boolean },
    tab_value: { type: String },
    tab_key: { type: String },
    deleted: { type: Boolean, default: false }
});

TopicSchema.plugin(BaseModel);
TopicSchema.index({create_at: -1});
TopicSchema.index({top: -1, last_reply_at: -1});
TopicSchema.index({author_id: 1, create_at: -1});

TopicSchema.virtual('tabName').get(function () {
   let tab = this.tab;
   let pair = _.find(config.tabs, function (_pair) {
       return _pair[0] === tab;
   });

   if(pair) {
       return pair[1];
   } else {
       return '';
   }
});

mongoose.model('Topic', TopicSchema);